/**
 * Flowise认证工具类
 * 处理Cube-Studio与Flowise之间的认证集成
 */

export interface CubeAuthData {
    user: {
        id: string
        username: string
        email: string
        role: string
        name: string
        first_name?: string
        last_name?: string
        is_active: boolean
        is_admin: boolean
    }
    permissions: Record<string, boolean>
    timestamp: number
    source: string
    isAuthenticated: boolean
    isGlobal: boolean
    token?: string
}

export class FlowiseAuthManager {
    private static instance: FlowiseAuthManager
    private authData: CubeAuthData | null = null
    private authCallbacks: Array<(authData: CubeAuthData) => void> = []
    private isInitialized = false

    private constructor() {}

    public static getInstance(): FlowiseAuthManager {
        if (!FlowiseAuthManager.instance) {
            FlowiseAuthManager.instance = new FlowiseAuthManager()
        }
        return FlowiseAuthManager.instance
    }

    /**
     * 初始化认证管理器
     */
    public initialize(): void {
        if (this.isInitialized) {
            return
        }

        console.log('初始化Flowise认证管理器')
        
        // 监听来自iframe的认证请求
        window.addEventListener('message', this.handleMessage.bind(this))
        
        this.isInitialized = true
    }

    /**
     * 处理消息事件
     */
    private handleMessage(event: MessageEvent): void {
        if (event.data.type === 'REQUEST_CUBE_AUTH') {
            console.log('收到Flowise认证请求')
            this.sendAuthInfo()
        }
    }

    /**
     * 获取认证信息并发送给Flowise
     */
    public async sendAuthInfo(): Promise<void> {
        try {
            console.log('开始获取Cube认证信息...')
            
            const response = await fetch('/myapp/flowise/auth', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`)
            }

            const authData: CubeAuthData = await response.json()
            console.log('获取到认证数据:', authData)

            this.authData = authData

            // 发送给所有iframe
            this.broadcastAuthData(authData)

            // 调用回调函数
            this.authCallbacks.forEach(callback => {
                try {
                    callback(authData)
                } catch (error) {
                    console.error('认证回调执行失败:', error)
                }
            })

        } catch (error) {
            console.error('获取认证信息失败:', error)
        }
    }

    /**
     * 广播认证数据到所有iframe
     */
    private broadcastAuthData(authData: CubeAuthData): void {
        const iframes = document.querySelectorAll('iframe')
        
        iframes.forEach((iframe, index) => {
            if (iframe.contentWindow) {
                console.log(`向iframe ${index} 发送认证信息`)
                
                try {
                    iframe.contentWindow.postMessage({
                        type: 'CUBE_AUTH',
                        data: authData
                    }, '*')
                } catch (error) {
                    console.error(`向iframe ${index} 发送消息失败:`, error)
                }
            }
        })

        // 特别处理Flowise iframe
        const flowiseIframe = document.getElementById('_frontendAppCustomFrame_') as HTMLIFrameElement
        if (flowiseIframe && flowiseIframe.contentWindow) {
            console.log('向Flowise iframe发送认证信息')
            
            // 多次尝试发送，确保接收到
            const sendMessage = () => {
                try {
                    flowiseIframe.contentWindow?.postMessage({
                        type: 'CUBE_AUTH',
                        data: authData
                    }, '*')
                } catch (error) {
                    console.error('向Flowise发送消息失败:', error)
                }
            }

            sendMessage()
            setTimeout(sendMessage, 500)
            setTimeout(sendMessage, 1000)
            setTimeout(sendMessage, 2000)
        }
    }

    /**
     * 添加认证回调
     */
    public onAuth(callback: (authData: CubeAuthData) => void): void {
        this.authCallbacks.push(callback)
        
        // 如果已有认证数据，立即调用回调
        if (this.authData) {
            try {
                callback(this.authData)
            } catch (error) {
                console.error('认证回调执行失败:', error)
            }
        }
    }

    /**
     * 获取当前认证数据
     */
    public getAuthData(): CubeAuthData | null {
        return this.authData
    }

    /**
     * 检查是否已认证
     */
    public isAuthenticated(): boolean {
        return this.authData !== null && this.authData.isAuthenticated
    }

    /**
     * 清除认证数据
     */
    public clearAuth(): void {
        this.authData = null
        console.log('认证数据已清除')
    }

    /**
     * 销毁认证管理器
     */
    public destroy(): void {
        window.removeEventListener('message', this.handleMessage.bind(this))
        this.authCallbacks = []
        this.authData = null
        this.isInitialized = false
        console.log('认证管理器已销毁')
    }
}

// 导出单例实例
export const flowiseAuthManager = FlowiseAuthManager.getInstance()

// 自动初始化
if (typeof window !== 'undefined') {
    flowiseAuthManager.initialize()
}
